/*
 * BrowseAction.java
 *
 * Created on March 27, 2005, 1:18 AM
 */

package tools;

import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

/**
 *
 * @author Keith
 */
public class BrowseAction extends AbstractAction {
  
  private JFileChooser fileChooser;
	private Document doc;
	private FileFilter filter;

  public BrowseAction( JFileChooser fc, Document doc, FileFilter filter ) {
		super( "Browse..." );
		setFileChooser( fc );
		setFileFilter( filter );
		setDocument( doc );
  }

  public BrowseAction( JFileChooser fc, Document doc ) {
		this( fc, doc, null );
  }

  public void setFileChooser( JFileChooser fileChooser ) {
    this.fileChooser = fileChooser;
  }

  public JFileChooser getFileChooser() {
    return fileChooser;
  }

  public void actionPerformed( ActionEvent e ){
		Component c = (Component)e.getSource();
		boolean done = false;

/*		FileFilter[] oldFilter = fileChooser.getChoosableFileFilters();
		for ( int i = 0; i < oldFilter.length; i++ ){
			fileChooser.removeChoosableFileFilter( oldFilter[ i ] );
		}
*/
		fileChooser.resetChoosableFileFilters();
		fileChooser.addChoosableFileFilter( filter );
//		fileChooser.addChoosableFileFilter( fileChooser.getAcceptAllFileFilter() );

		do {
			int retVal = fileChooser.showOpenDialog( c );
			if ( retVal != fileChooser.APPROVE_OPTION ){
				done = true;
			} else {
				java.io.File f = fileChooser.getSelectedFile();

				if ( f.exists() ){
					done = true;

					String fname = f.getAbsolutePath();

					try {
						doc.remove( 0, doc.getLength() );
						doc.insertString( 0, fname, null );
					} catch ( BadLocationException ex ){
						System.out.println( ex );
					}
				} else {
					int messageType = JOptionPane.ERROR_MESSAGE;
					int optionType = JOptionPane.YES_NO_OPTION;
					String title = "File does not exist";
					Object[] message = new Object[]{ "Specified file " + f.getAbsolutePath() +
																	" does not exists." };
					Object[] option = new String[]{ "Cancel" };
					JOptionPane.showOptionDialog( c, message, title, optionType,
																				messageType, null, option, option[0] );
				}
			}
		} while ( ! done );
  }

  public FileFilter getFileFilter() {
    return filter;
  }
  public void setFileFilter(FileFilter filter) {
    this.filter = filter;
  }
  public Document getDocument() {
    return doc;
  }
  public void setDocument(Document doc) {
    this.doc = doc;
  }
}
